import { FC, useEffect, useState } from "react";
import { Message, Modal } from "@arco-design/web-react";
import Button from "@mui/material/Button";
import { css } from "@emotion/css";
import { useAPI } from "../../hooks/useAPI.ts";
import dayjs from "dayjs";
import Typography from "@mui/material/Typography";
import { CardActions, CardMedia } from "@mui/material";
import CardContent from "@mui/material/CardContent";
import {
  IconCloseCircle,
  IconExclamationCircle,
  IconStop,
} from "@arco-design/web-react/icon";
import Grid from "@mui/material/Grid";

export interface ViewVideoRecordModalProps {
  videoList: string;
  id: number | string;
  userId: number | string;
  report: string;
  visible?: boolean;
  eventTime: string;
  action?: string | null;
  onClose?: () => void;
  refresh?: () => void;
  deleteRecord(id: number | string, videoList: string,userId: number | string,): void;
}

export const ViewVideoRecordModal: FC<ViewVideoRecordModalProps> = ({
  videoList,
  id,
  userId,
  report,
  visible,
  eventTime,
  action,
  onClose,
  refresh,
  deleteRecord,
}) => {
  // console.log("ViewVideoRecordModal", id, videoList);
  const api = useAPI();

  const handleReport = (type: number) => {
    if (type === 0) {
      deleteRecord(id, videoList,userId);
      onClose?.();
      refresh?.();
    } else {
      api
        .updateReport({
          id,
          userId,
          videoList,
          data: {
            method: type,
            report: {
              userId: window.localStorage.getItem("loggedUserId"),
              nickName: window.localStorage.getItem("loggedNickName"),
            },
            time: dayjs().format("YYYY-MM-DD HH:MM:s"),
          },
        })
        .then((r) => {
          if (r.data.code === 3001) {
            Message.info("操作成功");
          } else {
            Message.error("操作失败");
          }
          onClose?.();
          refresh?.();
        });
    }
  };

  const [gifKey, setGifKey] = useState<string | null>(null);

  useEffect(() => {
    if (!videoList) return; // Do nothing if videoList is empty

    // Set the initial gifKey when videoList is first provided
    // `/gif/files/src/playback/${videoList}.gif?${new Date().getTime()}`,
    setGifKey(
      `https://seysoai.com/api/ocs/playback/${videoList}.gif?${new Date().getTime()}`
    );

    // setGifKey(videoList);

    // setGifKey(
    //   `https://seysoai.com/api/ocs/playback/${videoList}.gif`
    // );

    // const interval = setInterval(() => {
    //   setGifKey(
    //     `https://seysoai.com/api/ocs/playback/${videoList}.gif?${new Date().getTime()}`
    //   );
    // }, 10000); // Refresh every 5 seconds

    return; // () => clearInterval(interval); // Clean up on unmount
  }, [videoList]);

  // @ts-ignore
  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      closable={false}
      unmountOnExit
      mountOnEnter
      footer={null}
      style={{
        width: "800px",
      }}
    >
      <div
        className={css`
          background: #fff;
          width: 100%;
        `}
      >
        <CardMedia
          sx={{
            // width: "600", // 宽度100%
            height: 500, // 高度自适应
            objectFit: "contain", // 保持比例完整显示
            backgroundColor: "#fff",
            aspectRatio: "9/6",
          }}
          image={gifKey ? gifKey : undefined}
          title="摔倒视频"
        />
        <CardContent>
          <Typography gutterBottom variant="h3" component="div">
            风险警报 {action ? action : ""}
          </Typography>
          {report !== "null" && report !== null && report !== undefined ? (
            <>
              <Typography variant="h6" sx={{ color: "text.secondary" }}>
                系统于：{eventTime}收到风险警报。在{JSON.parse(report).time}由
                {` ${JSON.parse(report).report.nickName} `}完成处理，
                {JSON.parse(report).method === 0
                  ? "该警报为系统误报。"
                  : "已安排人员上门处理。"}
              </Typography>
            </>
          ) : (
            <Typography variant="h6">请及时处理。</Typography>
          )}
        </CardContent>
        <CardActions style={{ margin: "0px 20px 6px 6px" }}>
          <Grid container spacing={2}>
            <Grid item>
              <Button
                variant="contained"
                color="success"
                startIcon={<IconStop />}
                onClick={() => handleReport(0)}
              >
                系统误报
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="contained"
                color="primary"
                startIcon={<IconExclamationCircle />}
                onClick={() => handleReport(2)}
              >
                人工处理
              </Button>
            </Grid>

            <Grid item>
              <Button
                variant="contained"
                color="secondary"
                startIcon={<IconCloseCircle />}
                onClick={() => {
                  onClose?.();
                }}
              >
                关闭
              </Button>
            </Grid>
          </Grid>
        </CardActions>
      </div>
    </Modal>
  );
};
